<!--
  分账规则表单组件
  @description 分账规则新增/编辑表单对话框
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.ruleName')" prop="ruleName">
            <el-input
              v-model="formData.ruleName"
              :placeholder="t('settle.splitRule.rules.ruleNameRequired')"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.merchantNo')" prop="merchantNo">
            <el-select
              v-model="formData.merchantNo"
              :placeholder="t('settle.splitRule.rules.merchantNoRequired')"
              style="width: 100%"
              filterable
              remote
              :remote-method="searchMerchants"
              :loading="merchantLoading"
            >
              <el-option
                v-for="merchant in merchantOptions"
                :key="merchant.merchantNo"
                :label="`${merchant.merchantNo} - ${merchant.merchantName}`"
                :value="merchant.merchantNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.ruleType')" prop="ruleType">
            <el-select
              v-model="formData.ruleType"
              :placeholder="t('settle.splitRule.rules.ruleTypeRequired')"
              style="width: 100%"
              @change="handleRuleTypeChange"
            >
              <el-option
                v-for="(label, value) in ruleTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item 
            v-if="formData.ruleType === SplitRuleTypeEnum.RATIO"
            :label="t('settle.splitRule.splitRatio')" 
            prop="splitRatio"
          >
            <el-input-number
              v-model="formData.splitRatio"
              :placeholder="t('settle.splitRule.rules.splitRatioRequired')"
              :min="0.01"
              :max="100"
              :precision="2"
              :step="0.01"
              style="width: 100%"
            />
            <span class="ml-5px">%</span>
          </el-form-item>
          <el-form-item 
            v-if="formData.ruleType === SplitRuleTypeEnum.AMOUNT"
            :label="t('settle.splitRule.splitAmount')" 
            prop="splitAmount"
          >
            <el-input-number
              v-model="formData.splitAmount"
              :placeholder="t('settle.splitRule.rules.splitAmountRequired')"
              :min="1"
              :max="999999999"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
            <span class="ml-5px">元</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.receiverType')" prop="receiverType">
            <el-select
              v-model="formData.receiverType"
              :placeholder="t('settle.splitRule.rules.receiverTypeRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in receiverTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.receiverAccount')" prop="receiverAccount">
            <el-input
              v-model="formData.receiverAccount"
              :placeholder="t('settle.splitRule.rules.receiverAccountRequired')"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.receiverName')" prop="receiverName">
            <el-input
              v-model="formData.receiverName"
              :placeholder="t('settle.splitRule.rules.receiverNameRequired')"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.splitRule.priority')" prop="priority">
            <el-input-number
              v-model="formData.priority"
              :placeholder="t('settle.splitRule.rules.priorityRequired')"
              :min="1"
              :max="999"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item :label="t('settle.common.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('settle.common.pleaseInput') + t('settle.common.remark')"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { 
  getSplitRuleApi, 
  createSplitRuleApi, 
  updateSplitRuleApi 
} from '@/api/settle/splitRule'
import { getMerchantListApi } from '@/api/settle/merchant'
import type { SplitRuleVO, SplitRuleCreateReqVO, SplitRuleUpdateReqVO, MerchantVO } from '@/api/settle/types'
import { SplitRuleTypeEnum, ReceiverTypeEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'SplitRuleForm' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formType = ref('')
const formData = ref<SplitRuleCreateReqVO>({
  ruleName: '',
  merchantNo: '',
  ruleType: SplitRuleTypeEnum.RATIO,
  splitRatio: undefined,
  splitAmount: undefined,
  receiverType: ReceiverTypeEnum.MERCHANT,
  receiverAccount: '',
  receiverName: '',
  priority: 1,
  remark: ''
})

// 商户选项
const merchantOptions = ref<MerchantVO[]>([])
const merchantLoading = ref(false)

// 选项数据
const ruleTypeOptions = {
  [SplitRuleTypeEnum.RATIO]: t('settle.splitRule.ruleTypes.ratio'),
  [SplitRuleTypeEnum.AMOUNT]: t('settle.splitRule.ruleTypes.amount')
}

const receiverTypeOptions = {
  [ReceiverTypeEnum.MERCHANT]: t('settle.splitRule.receiverTypes.merchant'),
  [ReceiverTypeEnum.PERSONAL]: t('settle.splitRule.receiverTypes.personal')
}

// 表单校验规则
const formRules = reactive<FormRules>({
  ruleName: [
    { required: true, message: t('settle.splitRule.rules.ruleNameRequired'), trigger: 'blur' }
  ],
  merchantNo: [
    { required: true, message: t('settle.splitRule.rules.merchantNoRequired'), trigger: 'change' }
  ],
  ruleType: [
    { required: true, message: t('settle.splitRule.rules.ruleTypeRequired'), trigger: 'change' }
  ],
  splitRatio: [
    { required: true, message: t('settle.splitRule.rules.splitRatioRequired'), trigger: 'blur' }
  ],
  splitAmount: [
    { required: true, message: t('settle.splitRule.rules.splitAmountRequired'), trigger: 'blur' }
  ],
  receiverType: [
    { required: true, message: t('settle.splitRule.rules.receiverTypeRequired'), trigger: 'change' }
  ],
  receiverAccount: [
    { required: true, message: t('settle.splitRule.rules.receiverAccountRequired'), trigger: 'blur' }
  ],
  receiverName: [
    { required: true, message: t('settle.splitRule.rules.receiverNameRequired'), trigger: 'blur' }
  ],
  priority: [
    { required: true, message: t('settle.splitRule.rules.priorityRequired'), trigger: 'blur' }
  ]
})

// 计算属性
const isUpdate = computed(() => formType.value === 'update')

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开弹窗
 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? t('settle.common.add') + t('settle.splitRule.title') : t('settle.common.edit') + t('settle.splitRule.title')
  formType.value = type
  resetForm()
  
  // 加载商户列表
  await loadMerchants()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getSplitRuleApi(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取分账规则详情失败:', error)
    } finally {
      formLoading.value = false
    }
  }
}

/**
 * 提交表单
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const data = { ...formData.value }
    
    // 根据规则类型处理数据
    if (data.ruleType === SplitRuleTypeEnum.RATIO) {
      data.splitAmount = undefined
    } else {
      data.splitRatio = undefined
      // 将元转换为分
      data.splitAmount = Math.round((data.splitAmount || 0) * 100)
    }
    
    if (isUpdate.value) {
      await updateSplitRuleApi(data as SplitRuleUpdateReqVO)
      ElMessage.success(t('settle.splitRule.tips.updateSuccess'))
    } else {
      await createSplitRuleApi(data)
      ElMessage.success(t('settle.splitRule.tips.createSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存分账规则失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    ruleName: '',
    merchantNo: '',
    ruleType: SplitRuleTypeEnum.RATIO,
    splitRatio: undefined,
    splitAmount: undefined,
    receiverType: ReceiverTypeEnum.MERCHANT,
    receiverAccount: '',
    receiverName: '',
    priority: 1,
    remark: ''
  }
  formRef.value?.resetFields()
}

/**
 * 规则类型变化处理
 */
const handleRuleTypeChange = () => {
  // 清空相关字段
  formData.value.splitRatio = undefined
  formData.value.splitAmount = undefined
}

/**
 * 加载商户列表
 */
const loadMerchants = async () => {
  try {
    merchantLoading.value = true
    const data = await getMerchantListApi(1) // 只获取审核通过的商户
    merchantOptions.value = data
  } catch (error) {
    console.error('加载商户列表失败:', error)
  } finally {
    merchantLoading.value = false
  }
}

/**
 * 搜索商户
 */
const searchMerchants = async (query: string) => {
  if (query) {
    // 这里可以实现远程搜索逻辑
    await loadMerchants()
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.ml-5px {
  margin-left: 5px;
}
</style>
